package com.cheche.dn.domain.user;

import com.cheche.dn.Result;
import com.cheche.dn.common.Page;
import com.cheche.dn.common.Pageable;
import com.cheche.dn.common.base.BaseController;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Controller - 用户
 * Created by cheshun on 15/9/16.
 */
@RestController
public class UserController extends BaseController {

    /**
     * 添加一个用户
     * @param user 用户属性
     * @return user
     */
    @RequestMapping(value = USERS_URL, method = RequestMethod.POST)
    public Object users(User user) {
        if (!isValid(user, User.Save.class)) {
            return currentValidError();
        }
        service.save(user);
        return Result.success("user", user);
    }

    /**
     * 获取当前登录用户
     * @return user
     */
    @RequestMapping(value = USERS_SELF_URL, method = RequestMethod.GET)
    public Object users() {
        return Result.success("user", currentUser());
    }

    /**
     * 获取指定用户信息
     * @param id ID
     * @return user
     */
    @RequestMapping(value = USERS_ID_URL, method = RequestMethod.GET)
    public Object users(@PathVariable Long id) {
        return Result.success("user", service.find(User.class, id));
    }

    /**
     * 获取用户列表
     * @param pn 页码
     * @param limit 每页数量
     * @param dt 数据类型
     * @return users
     */
    @RequestMapping(value = USERS_URL, method = RequestMethod.GET)
    public Object users(@RequestParam(defaultValue = "1") int pn,
                        @RequestParam(defaultValue = "10") int limit,
                        @RequestParam(defaultValue = Dt.PAGE) String dt) {
        Pageable pageable = new Pageable.Builder(pn, limit).build();
        if (dt.equals(Dt.LIST)) {
            List<User> users = service.findList(User.class, pageable);
            return Result.success("users", users);
        }
        Page<User> page = service.findPage(User.class, pageable);
        return Result.success("page", page);
    }

    @RequestMapping(value = USERS_URL, method = RequestMethod.DELETE)
    public Object users(@RequestParam("id") Long[] ids, @RequestParam int type) {
        if (type == 1) {
            service.delete(User.class, ids);
        }
        if (type == 2) {
            service.delete(User.class, ids[0]);
        }
        return Result.success();
    }

}
